package com.qf.team2.netdisc.controller;

import com.qf.team2.netdisc.common.base.BaseController;
import com.qf.team2.netdisc.common.pojo.entity.Document;
import com.qf.team2.netdisc.common.pojo.vo.RespResultVO;
import com.qf.team2.netdisc.service.DocumentFolderService;
import com.qf.team2.netdisc.service.DocumentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;

@Controller
@RequestMapping("document")
@Api(tags = "文件相关接口")
public class DocumentFolderUploadController extends BaseController<Object> {
    @Autowired
    private DocumentFolderService documentFolderService;

    @Autowired
    private DocumentService documentService;

    @ResponseBody
    @RequestMapping(value = "folder", method = RequestMethod.POST)
    @ApiOperation("文件夹上传接口")
    public RespResultVO<Object> folderUpload(@ApiParam("文件夹") HttpServletRequest request,
                                             @RequestParam(value = "upload", required = false)
                                                     MultipartFile[] file,
                                             @RequestParam(value = "rootId", required = false)
                                                     Integer rootId) throws IOException {
        System.out.println("folder");
        System.out.println(Arrays.toString(file));
        System.out.println(rootId);
        Document dbDocument = documentService.getDocumentById(rootId);
        String url = dbDocument.getUrl();
        try {
            String code = "";
            Cookie[] cks = request.getCookies();
            //遍历Cookie
            for (Cookie ck : cks) {
                //检索出自己的Cookie
                if ("userId".equals(ck.getName())) {
                    //记录Cookie的值
                    code = ck.getValue();
                    break;
                }
            }
            Integer userId = Integer.parseInt(code);
            Long filesize = documentFolderService.checkUserCapacity(userId, file);
            documentFolderService.folderUpload(file, userId, url, filesize);

        } catch (RuntimeException e) {
            e.printStackTrace();
            return failedResp(e.getMessage());
        }
        return null;
    }
}